<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本资料</span>
    </div>
    <!-- 表单 -->
    <el-form
      :model="userForm"
      :rules="userFormRules"
      ref="userForm"
      label-width="100px"
    >
      <el-form-item label="登录名称" prop="username">
        <el-input v-model="userForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input
          v-model="userForm.nickname"
          minlength="1"
          maxlength="10"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="userForm.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="update" type="primary">提交修改</el-button>
        <el-button @click="$refs.userForm.resetFields()">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: 'UserInfo',
  data () {
    return {
      userForm: {
        username: '',
        nickname: '',
        email: ''
      },
      // 表单的验证规则对象
      userFormRules: {
        nickname: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' },
          { pattern: /^\S{1,10}$/, message: '昵称必须是1-10位的非空字符串', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    // Vue 实例在初始化时, 优先初始化 data, computed 是晚于 data 初始化的, 所以不能在 data 中使用 computed 属性
    // 如果非要使用, 先设置默认值, 再到 created 时对 data 重新赋值
    // console.log(this.userInfo)
    // this.userForm.username = this.userInfo.username
    // this.userForm.nickname = this.userInfo.nickname
    // this.userForm.email = this.userInfo.email

    // 这样做不建议: 不能直接修改 vuex 的数据
    // this.userForm = this.userInfo

    // 浅拷贝
    this.userForm = { ...this.userInfo }

    // 原生 API 提供了一个方法
    // this.userForm = Object.assign({}, this.userInfo)
  },
  computed: {
    ...mapState('user', ['userInfo'])
  },
  methods: {
    update () {
      // 兜底校验
      this.$refs.userForm.validate(async valid => {
        if (!valid) return
        // 发请求
        const { data: res } = await this.$http.put('/my/userinfo', this.userForm)
        // 判断结果, 提醒用户
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 修改成功后重新发请求获取用户信息
        this.$store.dispatch('user/getUserInfo')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
